<?php
/*
*time：2017-02-24
*author:lisp
*/
class photoShare {
	/*
	*首页
	*/
	public function index($param){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$result = array();
		$userName=Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		$userId =  Session::$user['userId'];;

		$actId=$param->actId;
		$chanelId=$param->chanelId;
		if($actId > 0){
			$partake_id = photoShare::check_join($param);

			if($partake_id){
				$result['code'] = 1;
				$result['partake_id'] = $partake_id;
			}else{
				$result['code'] = 0;
				$result['openid'] = $userName;
				$activity_info = photoShare::get_activity_info($actId,$customerId);
				if($activity_info){
					$result['activity_info'] = $activity_info;
				}else{
					Output::instance()->resultCode(-1,"没有这个活动喔");
					return;
					// $result['code'] = -1;
					// $result['info'] = '活动信息不存在';
				}
				
				
				$result['userId'] = $userId;
			}
		}else{

			Output::instance()->resultCode(-1,"没有这个活动喔");
			return;
			
			
		}
       // {"activity_bg":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034532817.png"},"activity_main":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034374942.png"},"activity_index_img":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034315410.jpg,http://oss.mboxone.com/20170301/image/3/1488369034347122.jpg"},"activty_index_button":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034798097.png"},"activity_submit_button":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034625415.png"},"activity_submit_tip":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034135074.jpg,http://oss.mboxone.com/20170301/image/3/1488369034863193.jpg"},"activity_info_bg":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034387607.png"},"activity_info_submit":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034746508.png"},"activity_join_button":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034417155.png"},"show_share":{"src":"http://oss.mboxone.com/20170227/image/3/1488200864796426.png","title":"show_share_title","description":"show_share_description"}}

		Output::instance()->module('photoShare',"index")->object($result);
	}
    /*
    *获取参加过此活动的参与编号
    */
    public function check_join($param){
    	$retVal = Session::init();
    	$customerId = Session::$user['customerId'];
    	$userId =  Session::$user['userId'];;

    	$actId=$param->actId;
    	$chanelId=$param->chanelId;
    	// $userId = 22;
    	// $partake_id = S('partake_id_'.$customerId.'_'.$actId.'_'.$userId);
//    	if(!$partake_id){
    		$map = array();
    		$map['userId'] = $userId;
    		$map['activityId'] = $actId;
    		$map['cid'] = $customerId;
    		Session::switchCustomer(0);
    		$activity_partake_db = M('miactivity_partake');

    		$partake_id = $activity_partake_db->where($map)->getField('id');
    		if($partake_id > 0){
    			// S('partake_id_'.$customerId.'_'.$actId.'_'.$userId,$partake_id,3500*24);
    		}
//    	}
    	
    	 // dump($partake_id);
    	 // exit;
    	 // echo $activity_partake_db->_sql();
    	 // exit;
    	return $partake_id;
    }

	/*
	*立即参加按钮所对应页面
	*/
	public function join_now($param){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$result = array();
		$userName=Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		$userId = Session::$user['userId'];
		$actId=$param->actId;
		
		$partake_id = photoShare::check_join($param);
		if($partake_id){
			$result['code'] = 1;
			$result['partake_id'] = $partake_id;
		}else{
			$result['code'] = 0;
			$activity_info = photoShare::get_activity_info($actId,$customerId);
			$result['activity_info'] = $activity_info;
			$result['userId'] =  $userId;
			$result['customerId'] = $customerId;
		}
		Output::instance()->module('photoShare',"join_now")->object($result);
	}

	/*
	*获取活动信息
	*/
	private function get_activity_info($actId,$customerId){
		// $activity_info = S('activity_info_'.$actId.'_'.$customerId);
//		if(!$activity_info){
			$retVal = Session::init();
			$userName=Session::$user['userName'];
			Session::switchCustomer(0);
			$map = array();
			$map['deleted'] = 0;
			$map['fromCustomerId'] = $customerId;
			$activity_info = M("Miactivity")->field('deleted',true)->where($map)->find($actId);

			if($activity_info){
				$jsonstr = json_decode($activity_info['jsonstr'],true);
				$jsonstr['activity_index_img']['src'] = explode(',',$jsonstr['activity_index_img']['src']);

				$jsonstr['activity_submit_tip']['src'] = explode(',',$jsonstr['activity_submit_tip']['src']);
				$activity_info['jsonstr'] = $jsonstr;
				if($activity_info['accessTag'] && $activity_info['accessTag'] != ''){
					setAccessTags($activity_info['accessTag'],$userName,'photoShare',$activity_info['id']);
				}
			}
			// S('activity_info_'.$actId.'_'.$customerId,$activity_info,3600*24);
//		}
		
		return $activity_info;
	}
	/*
	*检测活动状态
	*/
	public  function check($param){
		$retVal = Session::init();
		if(!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$actId=$param->actId;
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$result = $map = array();
		$map = array();
		$map['deleted'] = 0;
		$map['id'] = $actId;
		$map['status'] = 1;
		$map['endTime'] = array('gt',date('Y-m-d H:i:s'));
		$map['startTime'] = array('lt',date('Y-m-d H:i:s'));
		$map['fromCustomerId'] = $customerId;
		$activity_info = M("Miactivity")->field('type,deleted',true)->where($map)->find();


		if($activity_info && is_array($activity_info)){
			if($activity_info['isLimitCount'] == 1){
				if($activity_info['limitCount'] <= $activity_info['partakeCount']){
					$result['code'] = 0;
					$result['info'] = '此活动参与人数已达上限，不可参加';
				}else{
					$result['code'] = 1;
				}
			}else{
				$result['code'] = 1;
			}
			
		}else{
			$result['code'] = 0;
			$result['info'] = '此活动尚未开始或已结束';
		}

		Output::instance()->module('photoShare',"check")->object($result);

	}
	/*
	*添加参加活动数据
	*/
	public function save_data($param){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$result = array();
		$userName=Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		$actId=$param->actId;

		$activity_info = photoShare::get_activity_info($actId,$customerId);
		
		if($activity_info){
			$time_now = date('Y-m-d H:i:s');
			if($activity_info['status'] == 1 && $activity_info['startTime'] < $time_now &&  $activity_info['endTime'] > $time_now){
				if($activity_info['isLimitCount'] == 1){
					if($activity_info['limitCount'] > $activity_info['partakeCount']){
						$sql = 'lock table '.C('DB_PREFIX').'miactivity read';
						M()->execute($sql);
						$result = photoShare::deal_data($param,$activity_info['partakeCount']);
						$sql = 'unlock tables';
						M()->execute($sql);

					}else{
						$result['code'] = 0;
						$result['info'] = '此活动参与人数已达上限，不可参加';
					}
				}else{
					$result = photoShare::deal_data($param,$activity_info['partakeCount']);
				}
				
			}else{
				$result['code'] = 0;
				$result['info'] = '此活动尚未开始或已结束';
			}
			
		}else{
			$result['code'] = 0;
			$result['info'] = '活动信息不存在';
		}

		Output::instance()->module('photoShare',"save_data")->object($result);
	}
	/*
	*具体处理参加活动的数据
	*/
	public function deal_data($param,$partakeCount){
		$retVal = Session::init();
		$result = array();
		$userName=Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		$customerId = $customerId?$customerId:'0';
		$userId = Session::$user['userId'];
		$userId = $userId?$userId:'0';
		$cid = $customerId;
		$fromUserId = $param->fromUserId;
		$fromUserId = $fromUserId?$fromUserId:'0';

		$channelId = $param->chanelId;
		$picUrls = $param->picUrls;
		$phone = $param->phone;
		$name = $param->name;
		$actId=$param->actId;
		$activityId = $actId;

		Session::switchCustomer(0);
		$activity_partake_db = M('miactivity_partake');
		$activity_photo_share_db = M('miactivity_photo_share');
		$activity_db = M('miactivity');
		$partake_map = array();
		$partake_map['cid'] = $cid;
		$partake_map['userId'] = $userId;
		$partake_map['activityId'] = $activityId;
		$createTime = date('Y-m-d H:i:s');
		$count = $activity_partake_db->where($partake_map)->count();
		if($count <= 0){

			/*新增获取ip对应的信息*/
			$ipInfo = self::getIp_agent();

			$activity_partake_db->startTrans();
			$partake_data = $photo_share_data = array();
			$partake_data['cid'] = $cid;
			$partake_data['userId'] = $userId;
			$partake_data['fromUserId'] = $fromUserId;
			$partake_data['activityId'] = $activityId;
			$partake_data['channelId'] = $channelId;
			$partake_data['createTime'] = $createTime;
			/*以下数据为新增*/
			$partake_data['ip_address'] = $ipInfo['ip_address'];
			$partake_data['ip_city'] = $ipInfo['city'];
			$partake_data['ip_province'] = $ipInfo['province'];
			$partake_data['user_agent'] = $ipInfo['userAgent'];

			$partake_result = $activity_partake_db->add($partake_data);
			$update_partakeCount = false;
			if($partake_result){
				$update_map = array();
				$update_map['fromCustomerId'] = $customerId;
				$update_map['id'] = $activityId;
				$partakeCount = intval($partakeCount) + 1;
				$update_data = array();
				$update_data['partakeCount'] = $partakeCount;
				$update_partakeCount = $activity_db->where($update_map)->save($update_data);
			}
			$photo_share_result = false;
			if($partake_result&&$partake_result>0){
				$photo_share_data['cid'] = $cid;
				$photo_share_data['userId'] = $userId;
				$photo_share_data['partakeId'] = $partake_result;
				$photo_share_data['name'] = $name;
				$photo_share_data['phone'] = $phone;
				$photo_share_data['picUrls'] = $picUrls;
				$photo_share_data['createTime'] = $createTime;
				$photo_share_data['activityId'] = $activityId;
				$photo_share_data['channelId'] = $channelId;
				Session::switchCustomer($cid);
				$user_map = array();
				$user_map['userId'] = $userId;
				$user_info = M('user_weixin_info')->field('nickname,headimgurl')->where($user_map)->find();
				$photo_share_data['nickname'] = $user_info['nickname'];
				$photo_share_data['headimgurl'] = $user_info['headimgurl'];
				$photoCount = count(explode(',', $picUrls));
				$photo_share_data['photoCount'] = $photoCount;
				$photo_share_result = $activity_photo_share_db->add($photo_share_data);
			}

			if($partake_result&&$photo_share_result&&$update_partakeCount){
				$activity_partake_db->commit();
				$result['code'] = 1;
				$result['partake_id'] = $partake_result;
				//$result['userId'] = $userId;
			}else{
				$activity_partake_db->rollback();
				$result['activity_partake_sql'] = $activity_partake_db->_sql();
				$result['activity_sql'] = $activity_db->_sql();
				$result['activity_photo_share_db_sql'] = $activity_photo_share_db->_sql();
				$result['code'] = 0;
				if(!$partake_result){
					$error = $activity_partake_db->getError();
				}elseif(!$update_partakeCount){
					$error = $activity_db->getError();
				}else{
					$error = $activity_photo_share_db->getError();
				}
				$error = $error?$error:"发生未知错误";
				$result['info'] = $error;
			}

		}else{
			$result['code'] = 0;
			$result['info'] = '你已经参加过本次活动';
		}
		return $result;

	}

	/*
	*晒图页面数据接口
	*/
	public function show($param){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$result = array();
		$userName=Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		$userId = Session::$user['userId'];
		$actId=$param->actId;
		$partake_id = $param->partake_id;
		$channelId = $param->chanelId;
		$fromUserId = $param->fromUserId;

		$partake_id_self = photoShare::check_join($param);
		if($partake_id_self &&$partake_id_self > 0){
			$result['code'] = 1;
			$result['partake_id'] = $partake_id_self;
		}
		$activity_info = photoShare::get_activity_info($actId,$customerId);
		Session::switchCustomer(0);
		$activity_photo_share_db = M('miactivity_photo_share');
		$activity_visit_db = M('miactivity_visit');


		if($partake_id && $partake_id > 0){
			if($fromUserId != $userId){
				/*新增获取ip对应的信息*/
				$ipInfo = self::getIp_agent();

				$visit_data = array();
				$visit_data['cid'] = $customerId;
				$visit_data['activityId'] = $actId;
				$visit_data['partakeId'] = $partake_id;
				$visit_data['channelId'] = $channelId;
				$visit_data['userId'] = $userId;
				$visit_data['fromUserId'] = $fromUserId;
				$visit_data['createTime'] = date('Y-m-d H:i:s');
				/*以下数据为新增*/
				$visit_data['ip_address'] = $ipInfo['ip_address'];
				$visit_data['ip_city'] = $ipInfo['city'];
				$visit_data['ip_province'] = $ipInfo['province'];
				$visit_data['user_agent'] = $ipInfo['userAgent'];

				$activity_visit_db->add($visit_data);
			}
			$map = array();
			$map['partakeId'] = $partake_id;
			// $map['']
			// $map['deleted'] = 0;
//            $photo_share_info = S('photo_share_info_'.$customerId.'_'.$actId.'_'.$partake_id);
//			if(!$photo_share_info){
				$photo_share_info = $activity_photo_share_db->field('name,phone,createTime,picUrls,partakeId')->where($map)->find();
//                S('photo_share_info_'.$customerId.'_'.$actId.'_'.$partake_id,$photo_share_info,3600*24);
//			}

			if($photo_share_info){
				$photo_share_info['picUrls'] = explode(',', $photo_share_info['picUrls']);
				$result['photo_share_info'] = $photo_share_info;
				
				// $visit_map  = array();
				$visit_map = ' EXISTS(select 1 from '.C('DB_PREFIX').'miactivity_visit b where a.userId=b.userId and b.cid = '.$customerId.' and b.partakeId = '.$partake_id.' and activityId = '.$actId.' )';
				$visit_map = ' a.userId in (select distinct userId from '.C('DB_PREFIX').'miactivity_visit b where b.cid = '.$customerId.' and b.partakeId = '.$partake_id.' and activityId = '.$actId.' )';
				// $visit_map['1'] = array('exp',$where);
				// $visit_map['partakeId'] = $partake_id;
				// $visit_map['cid'] = $customerId;
				// $visit_map['activityId'] = $actId;
				Session::switchCustomer($customerId);
				$user_weixin_info_db = M('user_weixin_info');
				$visit_list = $user_weixin_info_db->alias('a')
				->field('a.userId,a.nickname,a.headimgurl')
                ->where($visit_map)
                ->select();
				// $sql = 'select a.* from '.C('DB_PREFIX').$customerId.'_user_weixin_info a where exists(select 1 from B b where a.id=b.id)';
				// $visit_list = $activity_visit_db->alias('a')
				// ->join('left join wx_'.$customerId.'_user_weixin_info b on a.userId=b.userId')
				// ->field('a.userId,b.nickname,b.headimgurl')
				// ->distinct(true)
				// ->where($visit_map)->select();

			    // $result['sql'] = $activity_visit_db->_sql();
				$result['visit_list'] = $visit_list;
				$result['visit_count'] = count($visit_list);

				$result['activity_info'] = $activity_info;
				$result['userId'] =  $userId;

			}else{
				$result['code'] = 0;
				$result['info'] = '参加活动的信息不存在';
			}
			
		}else{
			$result['code'] = 0;
			$result['info'] = '参数不全';
		}

		Output::instance()->module('photoShare',"show")->object($result);
		
	}
	/*
	*测试
	*/
	public function test($param){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$result = array();
		$userName=Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		Output::instance()->module('photoShare',"test")->object($result);
	}

	/**
	 * 获取用户的ip以及user_agent信息
	 * @return array
	 */
	protected  static function getIp_agent(){
		$ipInfo = array();
		if($_SERVER['HTTP_HTTP_X_REAL_IP']){
			//nginx 代理模式下，获取客户端真实IP
			$realIp = $_SERVER['HTTP_HTTP_X_REAL_IP'];
		}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
			//客户端的ip
			$realIp = $_SERVER['HTTP_CLIENT_IP'];
		}elseif (isset($_SERVER['HTTP_HTTP_X_FORWARDED_FOR'])) {
			//浏览当前页面的用户计算机的网关
			$arr = explode(',', $_SERVER['HTTP_HTTP_X_FORWARDED_FOR']);
			$pos = array_search('unknown',$arr);
			if(false !== $pos) unset($arr[$pos]);
			$realIp = trim($arr[0]);
		}elseif (isset($_SERVER['REMOTE_ADDR'])) {
			//浏览当前页面的用户计算机的ip地址
			$realIp = $_SERVER['REMOTE_ADDR'];
		}else{
			$realIp=$_SERVER['REMOTE_ADDR'];
		}
		$userAgent = $_SERVER['HTTP_USER_AGENT'];
		$realIpInt = bindec(decbin(ip2long($realIp)));

		//查询ip对应的地址信息
		if($realIp){
			$cid = Session::$user['customerId'];
			Session::switchCustomer(0);
			$ipInfo_table = M('ip_info');

			$map = array();
			$map['start_ip_int'] = array('elt',$realIpInt);
			$map['end_ip_int'] = array('egt',$realIpInt);
			$result = $ipInfo_table->where($map)->find();
			if($result){
				$ipInfo['province'] = $result['province'];
				$ipInfo['city'] = $result['city'];
			}else{
				Log::write('客户端ip信息----:'.print_r($_SERVER, true));
				Log::write('查询ip信息-----'.$ipInfo_table->getLastSql());
			}
			Session::switchCustomer($cid);
		}

		$ipInfo['ip_address'] = $realIp;
		$ipInfo['userAgent'] = $userAgent;
		return $ipInfo;
	}
}